package com.gagakuai.session.defaluts;

import com.gagakuai.executor.ErrorContext;
import com.gagakuai.executor.Executor;
import com.gagakuai.mapping.Environment;
import com.gagakuai.session.*;
import com.gagakuai.transcation.Transaction;
import com.gagakuai.transcation.TransactionFactory;

import java.sql.Connection;


/*
 * @program: common-starters
 * @description: 默认工厂
 * @author: houhong
 * @create: 2023-06-29 20:37
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SqlSession openSession() {
        return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
    }

    @Override
    public SqlSession openSession(boolean autoCommit) {
        return null;
    }

    @Override
    public SqlSession openSession(Connection conn) {
        return null;
    }

    @Override
    public Configuration getConfiguration() {
        return null;
    }

    /*
     * @param level:事务隔离级别
     * @param autoCommit:是否自动提交
     * @param executorType:     执行器类型
     * @return {@link SqlSession}
     * @Author houhong
     * @Description 从数据源获取链接
     * @Date 8:52 下午 2023/6/29
     */
    private SqlSession openSessionFromDataSource(ExecutorType executorType, TransactionIsolationLevel level, boolean autoCommit) {


        Transaction tx = null;
        try {
            final Environment environment = configuration.getEnvironment();
            final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
            tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
            final Executor executor = configuration.newExecutor(tx, executorType);
            return new DefaultSqlSession(configuration, executor, autoCommit);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //todo
            ErrorContext.instance().reset();
        }

    }



    private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
        if (environment == null || environment.getTransactionFactory() == null) {
            return new ManagedTransactionFactory();
        }
        return environment.getTransactionFactory();
    }

}